#ifndef CLIENT_SOCKET_HANDLER
#define CLIENT_SOCKET_HANDLER

#include <stdio.h>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "Defines.cpp"

class ClientSocketHandler
{
private:
    char _buff[10];
    int _buffLength = 0;
    int _currentPoint = 0;
    int _clientSocket;

    bool ReadSocket()
    {
        _buffLength = recv(_clientSocket, _buff, sizeof(_buff), MSG_NOSIGNAL);
        if (_buffLength <= 0)
        {
            PrintLine("读取客户端内容失败");
            return false;
        }
        return true;
    }

public:
    ClientSocketHandler(int clientSocket)
    {
        _clientSocket = clientSocket;
        ReadSocket();
        _currentPoint = 0;
    }

    bool GetNextByte(char *c)
    {
        if (_currentPoint == _buffLength)
        {
            if(ReadSocket() == false)
            {
                return false;
            }
            _currentPoint = 0;
        }
        *c = _buff[_currentPoint++];
        return true;
    }

    bool WriteSocket(const char *buff, int length)
    {
        int ret = send(_clientSocket, buff, length, MSG_NOSIGNAL);
        if(ret != length)
        {
            return false;
        }
        return true;
    }

    ~ClientSocketHandler()
    {
        close(_clientSocket);
    }
};

#endif